/* 
The License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */
 
package com.photobucket.webapi.service
{
	import com.photobucket.webapi.events.PhotobucketServiceEvent;
	import com.photobucket.webapi.events.PhotobucketServiceExceptionEvent;
	import com.photobucket.webapi.oauth.IOAuthRequest;
	
	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.TimerEvent;
	import flash.net.URLLoader;
	import flash.utils.Timer;

	/**
	* Event dispatched when an exception is encounterd 
	*/
	[Event(name="exception", type="com.photobucket.webapi.events.PhotobucketServiceExceptionEvent")]
	/**
	* Event dispatched when the channel is complete and ready for a new request
	*/
	[Event(name="channelComplete",type="com.photobucket.webapi.events.PhotobucketServiceEvent")]
	/**
	 * Class that will make a URL request using an internal URLLoader or a FileReference if supplied on an IOAuthRequest.  It will handle the events and respond to the provided responder with
	 * the contents of the responce or a PhotopbucketException if an Error occurs. 
	 * @author jlewark
	 * 
	 */
	public class PhotobucketChannel extends EventDispatcher
	{
		private var loader:URLLoader;
		private var _request:IOAuthRequest;
		private var lastResponceCode:int;
		private var timeoutTimer:Timer;
		
		 
		/**
		 * Takes an IOAuthRequest Object and makes the request againist the photobucket servers and attaches the event handlers
		 * nessecary.  Also starts a timer to capture timeouts of the URLLoader since these are not always captured. 
		 * @param request
		 * 
		 */
		public function load(request:IOAuthRequest):void {
			try {
				lastResponceCode = 0;
				_request = request;
				if (_request.file == null) {
					if (loader == null) {
						loader = new URLLoader();
						loader.addEventListener(Event.COMPLETE, onComplete);
						loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus, false, 1);
						loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
						loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
					}
					if (timeoutTimer == null) {
						timeoutTimer = new Timer(90000, 1);
						timeoutTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimeoutTimerComplete);
					}
					if (timeoutTimer.running) {
						timeoutTimer.stop();
					}
					timeoutTimer.start();
					loader.load(request.getURLRequest());
				} else {
					_request.file.addEventListener(IOErrorEvent.IO_ERROR, onIOError, false, 0, true);
					_request.file.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus, false, 0, true);
					_request.file.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError, false, 0, true);
					_request.file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onDataComplete, false, 0, true);
					_request.file.upload(request.getURLRequest(), "uploadfile");
				}
			} catch(error:Error) {
				onFault(new PhotobucketException(0, error.errorID, error.message));
				this.dispatchEvent(new PhotobucketServiceEvent(PhotobucketServiceEvent.CHANNEL_COMPLETE));
			}

		}
		
		/**
		 * Passes the results onto the IOAuthRequest Object's result handler if present 
		 * @param object
		 * 
		 */
		protected function onResult(object:Object):void {
			if (_request.result != null) {
				_request.result(object);
			}
			_request = null;
			this.dispatchEvent(new PhotobucketServiceEvent(PhotobucketServiceEvent.CHANNEL_COMPLETE));
		}
		
		/**
		 * Passes the Fault onto the IOAuthRequest Object's fault handler if present
		 * @param fault
		 * 
		 */
		protected function onFault(fault:PhotobucketException):void {
			dispatchEvent(new PhotobucketServiceExceptionEvent(PhotobucketServiceExceptionEvent.EXCEPTION, fault, _request));
			//trace(fault.message);
			if (_request.fault != null) {
				_request.fault(fault);
			}
			_request = null;
			this.dispatchEvent(new PhotobucketServiceEvent(PhotobucketServiceEvent.CHANNEL_COMPLETE));
		}

		/**
		 * Takes the API Response and checks the status.  Passes sucessful results to the result handler and faults to the fault handler 
		 * @param object
		 * 
		 */
		protected function onData(object:Object):void {
			try {
				//trace(object.toString());
				var xml:XML = new XML(object);
				//trace(xml.toXMLString());
			} catch (error:Error) {
				onFault(new PhotobucketException(lastResponceCode, error.errorID, error.message));
				_request = null;
				return;
			}	
			if (xml.status == "OK") {
				try {
					var content:XMLList = xml.child("content");
					//trace(content.toXMLString());
					onResult(XML(content[0]));
				} catch (error:Error) {
					onResult(new XML());
				}
			} else {
				onFault(new PhotobucketException(lastResponceCode, xml.code, xml.toXMLString()));
			}
		
		}
	
		/**
		 * File Upload Response Handler 
		 * @param event
		 * 
		 */
		protected function onDataComplete(event:DataEvent):void {
			if (timeoutTimer != null) {
				if (timeoutTimer.running) {
					timeoutTimer.stop();
				}
			}
			if (_request.file != null) {
				_request.file.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
				_request.file.removeEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
				_request.file.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
				_request.file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onDataComplete);
			}
			onData(event.data);
		}
		
		/**
		 * API Response Handler
		 * @param event
		 * 
		 */
		protected function onComplete(event:Event):void {
			if (timeoutTimer != null) {
				if (timeoutTimer.running) {
					timeoutTimer.stop();
				}
			}
			trace(loader.data);
			var oauth:RegExp = /oauth_token=.*&oauth_token_secret=.*/;
			if (oauth.test(loader.data.toString())) {
				onResult(loader.data);				
			} else {
				onData(loader.data);
			}
		}
		
		/**
		 * HTTP Status Handler (used to capture HTTP Response Codes)
		 * Most of the time in Flash Player this is 0 
		 * @param event
		 * 
		 */
		protected function onHTTPStatus(event:HTTPStatusEvent):void {
			lastResponceCode = event.status;
		}
		
		/**
		 * IO Error Handler 
		 * @param event
		 * 
		 */
		protected function onIOError(event:IOErrorEvent):void {
			if (timeoutTimer != null) {
				if (timeoutTimer.running) {
					timeoutTimer.stop();
				}
			}
			onFault(new PhotobucketException(lastResponceCode, 100, event.text));
			
		}
		
		/**
		 * Security Error Handler
		 * @param event
		 * 
		 */
		protected function onSecurityError(event:SecurityErrorEvent):void {
			if (timeoutTimer != null) {
				if (timeoutTimer.running) {
					timeoutTimer.stop();
				}
			}
			onFault(new PhotobucketException(lastResponceCode, 100, event.text));
		}
		
		/**
		 * Timeout Handler 
		 * @param event
		 * 
		 */
		protected function onTimeoutTimerComplete(event:TimerEvent):void {
			if (timeoutTimer != null) {
				if (timeoutTimer.running) {
					timeoutTimer.stop();
				}
			}
			onFault(new PhotobucketException(0, 5503, "The api call has timed out ofter 65 seconds"));
		}

	}
}